package main
{
	import loader.*;
	
	import mx.controls.Label;
	
	import net.URI;
	
	public class LoaderMng
	{
		protected var loadQueue:Vector.< LoadRequest > = new Vector.<LoadRequest>();
		
		protected var isLoading:Boolean;
		
		
		protected static var _instance:LoaderMng;
		
		public function LoaderMng()
		{
			if( _instance )
			{
				throw new Error( "LoaderMng it is a sigleton" );
			}
		}
		
		public static function instance():LoaderMng
		{
			if( !_instance ) _instance = new LoaderMng();
			
			return _instance;
		}
		
		
		public function loadModule( moduleName:String, desc:String, onProgress:Function, onComplete:Function, onError:Function = null ):void
		{
			var loaderObj:ModuleLoader = new ModuleLoader();
			
			var request:LoadRequest = new LoadRequest( loaderObj,  moduleName, desc, onProgress, onComplete, onError ); 
			
			addLoadRequest( request );
		}
		
		public function loadData( url:String, desc:String, onProgress:Function, onComplete:Function, onError:Function = null ):void
		{
			var loaderObj:DataLoader = new DataLoader();
			
			var request:LoadRequest = new LoadRequest( loaderObj,  url, desc, onProgress, onComplete, onError ); 
			
			addLoadRequest( request );
		}
		
		public function loadImage( url:String, desc:String,  onProgress:Function, onComplete:Function, onError:Function = null ):void
		{
			var loaderObj:ImageLoader = new ImageLoader();
			
			var request:LoadRequest = new LoadRequest( loaderObj,  url, desc, onProgress, onComplete, onError ); 
			
			addLoadRequest( request );
		}
		
		
		public function addLoadRequest(  loadRequest:LoadRequest  ):void
		{
			loadQueue.push( loadRequest );
			
			if( !isLoading )
			{
				startLoad();
			}
			
		}
		
		
		protected function startLoad():void
		{	
			//ViewMng.instance().showLoading();
			if( !isLoading )
			{
				isLoading = true;
			}
			
			//这里不能直接shift,因为一旦shift掉了,loader就会被回收,从而无法触发loader的ready事件.
			var request:LoadRequest = loadQueue[0];
			
			var completedHandler:Function = function( loaderObj:AbstractLoader )
			{	
				if( request.onCompleted is Function )
				{
					request.onCompleted( loaderObj );
				}
				
				loadQueue.shift();
				
				if( loadQueue.length > 0 )
				{
					startLoad();
				}
				else
				{
					ViewMng.instance().hideLoading();
					isLoading = false;
				}
				
			};
			
			var progressHandler:Function = function( desc:String, loadedBytes:int, 
													 totalLoadedBytes:int,  speed:Number, percent:Number )
			{
				ViewMng.instance().progressLoading( desc, loadedBytes, totalLoadedBytes, speed, percent );
				
				if( request.onProgress is Function )
				{
					request.onProgress( desc, loadedBytes, totalLoadedBytes, speed, percent );
				}
			};
			
			request.loaderObj.startLoad( request.url, request.desc, progressHandler, completedHandler, request.onError );
			
		}
		
		
		
		
		
		
		
	}
}